import request from '../../../utils/unirequest';
import type { AxiosResponse } from '../../../type/common';
import type { GetResponse, SearchResponse, SearchRequest, GetRequest, GetEducationResponse, GetFamilyResponse, GetWorkResponse, GetEducationDetailResponse, GetFamilyDetailResponse, GetWorkDetailResponse, ISysPersonRepairBillVm, ISysPersonRepairBill, ISysPersonEducation, ISysPersonEducationVm, ISysPersonFamily, ISysPersonFamilyVm, ISysPersonWork, ISysPersonWorkVm, IRecognizeIdentityCardRequest, IRecognizeIdentityCardResponse, ISysOrg, ISysGroup, ISysJobPosition, ISysPersonResumeView, ISysPersonProfessionalTitleView, ISysPersonResumeVm, ISysPersonResume, ISysPersonProfessionalTitle, ISysPersonProfessionalTitleVm, ISysHrTransferRequestBill, ISysPersonRepairBillApproveRequest, IValidatePortraitRequest, IValidatePortraitResponse } from './interface';

export default function useActivityApi() {
  // HR人员接口
  return {
    // 获取人员列表
    search: (data: SearchRequest): Promise<AxiosResponse<SearchResponse[]>> =>
      request.post("/api/sysperson/search", data),
    // 获取档案补录列表
    searchRepairBill: (data: SearchRequest): Promise<AxiosResponse<SearchResponse[]>> =>
      request.post("/api/SysPersonRepairBill/Search", data),
    // 获取档案补录详情
    getRepairBill: (id: string | number): Promise<GetResponse> =>
      request.get(`/api/SysPersonRepairBill/${id}`),
    // // 获取基础信息
    get: (id: string | number): Promise<GetResponse> =>
      request.get(`/api/SysPerson/${id}`),
    // 获取教育经历列表
    getEducation: (data: GetRequest): Promise<AxiosResponse<GetEducationResponse[]>> =>
      request.post(`/api/SysPersonEducation/Search`, data),
    // 获取家庭成员列表
    getFamily: (data: GetRequest): Promise<AxiosResponse<GetFamilyResponse[]>> =>
      request.post(`/api/SysPersonFamily/Search`, data),
    // 获取工作经历列表
    getWork: (data: GetRequest): Promise<AxiosResponse<GetWorkResponse[]>> =>
      request.post(`/api/SysPersonWork/Search`, data),
    // 获取人员履历列表
    getEmployeeResume: (data: GetRequest): Promise<AxiosResponse<ISysPersonResumeView[]>> =>
      request.post(`/api/SysPersonResume/Search`, data),
    // 获取荣誉职称列表
    getHonorTitle: (data: GetRequest): Promise<AxiosResponse<ISysPersonProfessionalTitleView[]>> =>
      request.post(`/api/SysPersonProfessionalTitle/Search`, data),
    // 获取教育经历详情
    getEducationDetail: (id: string | number): Promise<GetEducationDetailResponse> =>
      request.get(`/api/SysPersonEducation/${id}`),
    // 获取家庭成员详情
    getFamilyDetail: (id: string | number): Promise<GetFamilyDetailResponse> =>
      request.get(`/api/SysPersonFamily/${id}`),
    // 获取工作经历详情
    getWorkDetail: (id: string | number): Promise<GetWorkDetailResponse> =>
      request.get(`/api/SysPersonWork/${id}`),
    // 获取人员履历详情
    getEmployeeResumeDetail: (id: string | number): Promise<ISysPersonResumeVm> =>
      request.get(`/api/SysPersonResume/${id}`),
    // 获取荣誉职称详情
    getHonorTitleDetail: (id: string | number): Promise<ISysPersonProfessionalTitleVm> =>
      request.get(`/api/SysPersonProfessionalTitle/${id}`),
    // 保存档案补录
    editRepairBill: (data: ISysPersonRepairBillVm): Promise<AxiosResponse<ISysPersonRepairBill>> =>
      request.put(`/api/SysPersonRepairBill/Edit`, data),
    // 系统人员维修单审批
    approveRepairBill: (data: ISysPersonRepairBillApproveRequest, tag?: string): Promise<ISysPersonRepairBill> => {
      const url = tag ? `/api/SysPersonRepairBill/approve?tag=${tag}` : '/api/SysPersonRepairBill/approve';
      return request.post(url, data);
    },
    // 新增学习经历
    addEducation: (data: ISysPersonEducationVm): Promise<ISysPersonEducation> =>
      request.post(`/api/SysPersonEducation/Add`, data),
    // 新增家庭成员
    addFamily: (data: ISysPersonFamilyVm): Promise<ISysPersonFamily> =>
      request.post(`/api/SysPersonFamily/Add`, data),
    // 新增工作经历
    addWork: (data: ISysPersonWorkVm): Promise<ISysPersonWork> =>
      request.post(`/api/SysPersonWork/Add`, data),
    // 新增人员履历
    addEmployeeResume: (data: ISysPersonResumeVm): Promise<ISysPersonResume> =>
      request.post(`/api/SysPersonResume/Add`, data),
    // 新增荣誉职称
    addHonorTitle: (data: ISysPersonProfessionalTitleVm): Promise<ISysPersonProfessionalTitle> =>
      request.post(`/api/SysPersonProfessionalTitle/Add`, data),
    // 删除学习经历
    deleteEducation: (data: string[]) =>
      request.post(`/api/SysPersonEducation/BatchDelete`, data),
    // 删除家庭成员
    deleteFamily: (data: string[]) =>
      request.post(`/api/SysPersonFamily/BatchDelete`, data),
    // 删除工作经历
    deleteWork: (data: string[]) =>
      request.post(`/api/SysPersonWork/BatchDelete`, data),
    // 删除人员履历
    deleteEmployeeResume: (data: string[]) =>
      request.post(`/api/SysPersonResume/BatchDelete`, data),
    // 删除荣誉职称
    deleteHonorTitle: (data: string[]) =>
      request.post(`/api/SysPersonProfessionalTitle/BatchDelete`, data),
    // 识别身份证
    recognizeIdentityCard: (data: IRecognizeIdentityCardRequest): Promise<IRecognizeIdentityCardResponse> =>
      request.post(`/api/_account/RecognizeIdentityCard`, data),
    // 下载文件 - 使用UniApp的downloadFile API
    downloadFile: (fileId: string, fileName?: string) => {
      return new Promise((resolve, reject) => {
        const downloadUrl = `${import.meta.env.VITE_BASE_URL}/api/_file/DownloadFile/${fileId}`;

        uni.downloadFile({
          url: downloadUrl,
          header: {
            // 如果需要认证token，从storage获取
            Authorization: uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : ''
          },
          success: (res) => {
            if (res.statusCode === 200) {
              // 下载成功，可以选择打开文件或预览
              resolve(res.tempFilePath);
            } else {
              reject(new Error(`下载失败，状态码：${res.statusCode}`));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },

    // 预览文件 - 结合下载和预览
    previewFile: async (fileId: string, fileName?: string) => {
      try {
        const tempFilePath = await new Promise<string>((resolve, reject) => {
          const downloadUrl = `${import.meta.env.VITE_BASE_URL}/api/_file/DownloadFile/${fileId}`;

          uni.downloadFile({
            url: downloadUrl,
            header: {
              Authorization: uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : ''
            },
            success: (res) => {
              if (res.statusCode === 200) {
                resolve(res.tempFilePath);
              } else {
                reject(new Error(`下载失败，状态码：${res.statusCode}`));
              }
            },
            fail: reject
          });
        });

        // 预览文档
        uni.openDocument({
          filePath: tempFilePath,
          showMenu: true, // 显示菜单，允许用户保存等操作
          success: () => {
            console.log('文件预览成功');
          },
          fail: (err) => {
            console.error('文件预览失败:', err);
            uni.showToast({
              title: '文件预览失败',
              icon: 'none'
            });
          }
        });
      } catch (error) {
        console.error('文件下载失败:', error);
        uni.showToast({
          title: '文件下载失败',
          icon: 'none'
        });
      }
    },
    // 获取人事组织（公司）列表
    getOrgList: (): Promise<ISysOrg[]> =>
      request.get(`/api/SysPerson/GetSysOrgs`),
    // 获取部门列表
    getGroupList: (): Promise<ISysGroup[]> =>
      request.get(`/api/SysPerson/GetSysGroups`),
    // 获取岗位列表
    getJobPositionList: (): Promise<ISysJobPosition[]> =>
      request.get(`/api/SysPerson/GetSysJobPositions`),
    // 获取部门树
    GetParentsTree: (): Promise<ISysHrTransferRequestBill[]> =>
      request.get(`/api/common/GetGroups?auth=false`),
    // 获取资质类别
    GetSysPersonProfessionalTitleTypes: (): Promise<ISysJobPosition[]> =>
      request.get(`/api/SysPersonProfessionalTitle/GetSysPersonProfessionalTitleTypes`),
    // 获取部门下的岗位列表
    GetSysJobPositions: (groupId: string): Promise<ISysJobPosition[]> =>
      request.get(`/api/common/getjobpositions?groupId=${groupId}`),
    // 人像验证接口
    validatePortrait: (data: IValidatePortraitRequest): Promise<IValidatePortraitResponse> =>
      request.post('/api/_account/GenerateIdPhoto', data),
  };
}